package com.b3log.baidu.pcs.common;


import java.io.*;


public final class IOUtil {
    
    private IOUtil() {
    }
    
    public static boolean isFile(String path){
        File file = new File(path);
        boolean isFile = file.isFile();
        return isFile;
    }
    
    public static ByteBuffer toByteBuffer(InputStream inputStream) throws IOException {
        int intDataCount;
        try {
            intDataCount = inputStream.available();
        } catch (IOException e) {
            throw e;
        }
        ByteBuffer bbData = new ByteBuffer(intDataCount);
        boolean blnDone = false;
        while (!blnDone) {
            int intDataByte;
            try {
                intDataByte = inputStream.read();
            } catch (IOException e) {
                throw e;
            }
            if (intDataByte < 0){
                blnDone = true;
            }else{
                bbData.append((byte) intDataByte);
            }
        }
        return bbData;
    }
    
    public static byte[] toBytes(InputStream inputStream) throws IOException {
        return toByteBuffer(inputStream).toBytes();
    }
    
    public static String toString(InputStream inputStream) throws IOException {
        return toByteBuffer(inputStream).toString();
    }
    

    public static File bytes2File(byte[] b, String outputFile){
        BufferedOutputStream stream = null;
        File file = null;
        try{
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            if (stream != null){
                try{
                    stream.close();
                } catch (IOException e1){
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }
    
    public static byte[] inputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }
    
    public static InputStream byteToInputStream(byte[] data){
        InputStream is = new ByteArrayInputStream(data); 
        return is;
    }
}
